package com.ydy.quartz.service.impl;

import com.ydy.quartz.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailServiceImpl implements MailService {

    private static Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    //发送者
    @Value("${mail.fromMail.addr}")
    private String from;

    @Override
    public Map<String, Object> sendAttachmentsMail(String subject, String content, String filePath,String to) {
        LOGGER.info("发送邮件主题{},内容{},附件{},收件人{}",subject,content,filePath,to);
        MimeMessage message = mailSender.createMimeMessage();
        Map<String, Object> map = new HashMap<>();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            // 发送附件
            File file = new File(filePath);
            file = ResourceUtils.getFile(file.getAbsolutePath());
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));

            System.out.println(fileName);
            //添加多个附件可以使用多条 helper.addAttachment(fileName,file);
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            map.put("code", 1);
            map.put("message", "发送成功");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",0);
            map.put("message","发送失败");
            return map;
        }finally {

        }
    }

}
